<?php
declare (strict_types = 1);

namespace app\controller\api;

use app\BaseController;
use app\model\Order;
use app\model\Payment as PaymentModel;
use app\model\User as UserModel;
use app\service\WechatService;
use think\facade\Db;

class Payment extends BaseController
{
    protected $wechatService;
    protected $user;
    
    public function __construct()
    {
        parent::__construct();
        $this->wechatService = new WechatService();
        
        // 检查用户登录状态
        $token = input('token');
        $this->user = UserModel::where('token', $token)->find();
        if (!$this->user) {
            return json(['code' => 401, 'msg' => '请先登录']);
        }
    }
    
    /**
     * 创建支付订单
     */
    public function create()
    {
        $amount = input('post.amount/f');
        if ($amount <= 0) {
            return json(['code' => 1, 'msg' => '支付金额必须大于0']);
        }
        
        Db::startTrans();
        try {
            // 创建订单
            $order = new Order;
            $order->order_no = Order::generateOrderNo();
            $order->user_id = $this->user->id;
            $order->total_amount = $amount;
            $order->save();
            
            // 创建支付记录
            $payment = new PaymentModel;
            $payment->order_no = $order->order_no;
            $payment->amount = $amount;
            $payment->save();
            
            // 调用微信支付
            $result = $this->wechatService->unifiedOrder(
                $order->order_no,
                $amount,
                '商品购买',
                $this->user->openid
            );
            
            if (!$result) {
                throw new \Exception('创建支付订单失败');
            }
            
            // 生成支付参数
            $params = $this->wechatService->generateJsApiParams($result['prepay_id']);
            
            Db::commit();
            return json(['code' => 0, 'data' => $params]);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage()]);
        }
    }
    
    /**
     * 支付回调
     */
    public function notify()
    {
        $xml = file_get_contents('php://input');
        $data = $this->wechatService->xmlToArray($xml);
        
        // 验证签名
        $sign = $data['sign'];
        unset($data['sign']);
        if ($sign !== $this->wechatService->generateSign($data)) {
            return '<xml><return_code>FAIL</return_code><return_msg>签名验证失败</return_msg></xml>';
        }
        
        // 处理支付结果
        if ($data['return_code'] == 'SUCCESS' && $data['result_code'] == 'SUCCESS') {
            Db::startTrans();
            try {
                // 更新支付记录
                $payment = PaymentModel::where('order_no', $data['out_trade_no'])->find();
                if ($payment) {
                    $payment->transaction_id = $data['transaction_id'];
                    $payment->status = 1;
                    $payment->save();
                    
                    // 更新订单状态
                    $order = Order::where('order_no', $data['out_trade_no'])->find();
                    if ($order) {
                        $order->status = 1;
                        $order->pay_time = date('Y-m-d H:i:s');
                        $order->save();
                    }
                }
                
                Db::commit();
                return '<xml><return_code>SUCCESS</return_code><return_msg>OK</return_msg></xml>';
            } catch (\Exception $e) {
                Db::rollback();
                return '<xml><return_code>FAIL</return_code><return_msg>处理失败</return_msg></xml>';
            }
        }
        
        return '<xml><return_code>FAIL</return_code><return_msg>支付失败</return_msg></xml>';
    }
    
    /**
     * 查询支付状态
     */
    public function query()
    {
        $orderNo = input('order_no');
        if (!$orderNo) {
            return json(['code' => 1, 'msg' => '参数错误']);
        }
        
        $payment = PaymentModel::where('order_no', $orderNo)->find();
        if (!$payment) {
            return json(['code' => 1, 'msg' => '支付记录不存在']);
        }
        
        return json(['code' => 0, 'data' => $payment]);
    }
} 